package com.gz.moreaseManager.config;

import com.gz.moreaseManager.utils.SecureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {

	private final SelfUserDetailsService userDetailsService;

	@Autowired
	public SelfAuthenticationProvider(SelfUserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String userName = authentication.getName();
		String password = authentication.getCredentials().toString();
		SelfUserDetails userDetails = (SelfUserDetails) userDetailsService.loadUserByUsername(userName);
		if (userDetails == null)
			throw new UsernameNotFoundException(String.format("用户'%s'不存在", userName));
		else if (password == null)
			throw new BadCredentialsException(String.format("用户'%s'密码不能为空", userName));
		password = SecureUtil.builder().mineEncode(password, userName);
		if (!password.equals(userDetails.getPassword()))
			throw new BadCredentialsException("密码错误");
		return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
	}

	/**
	 * 是否可以提供输入类型的认证服务
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}
}